package threadProblem;

public class ThreadAdvantage {
    private static final int count = 10_0000_0000;

    //并发运行
    public static void concurrency() throws InterruptedException {
        //记录开始计算的时间
        long begin = System.nanoTime();
        //子线程计算a值
        Thread thread = new Thread(){
            @Override
            public void run() {
                int a = 0;
                for(int i = 0; i < count; i++){
                    a--;
                }
            }
        };
        thread.start();
        //主线程计算b值
        int b = 0;
        for (int i = 0; i < count; i++){
            b--;
        }
        //等待子线程计算完
        thread.join();
        //记录结束的时间
        long end = System.nanoTime();
        //统计耗时并打印
        double ms = (end - begin) * 1.0 / 1000 / 1000;
        System.out.println("concurrency 耗时：" + ms + "毫秒");
    }

    //串行运行
    public static void serial(){
        //记录开始计算的时间
        long begin = System.nanoTime();
        //主线程串行计算a和b的值
        int a = 0;
        for (int i = 0; i < count; i++){
            a--;
        }

        int b = 0;
        for (int i = 0; i < count; i++){
            b--;
        }
        //记录计算结束的时间
        long end = System.nanoTime();
        //统计串行计算的耗时并打印
        double ms = (end - begin) * 1.0 / 1000 / 1000;
        System.out.println("concurrency 耗时：" + ms + "毫秒");
    }

    public static void main(String[] args) throws InterruptedException {
        //使用并发方式
        concurrency();
        //使用串行方式
        serial();
    }
}
